package com.peanut.devlibrary.util;

import android.annotation.SuppressLint;
import android.os.Environment;

import com.tencent.mars.xlog.Log;

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;

/**
 * Created by anonymouslystudio on 2017/6/6.
 */

public class FileUtil {
    private static final String TAG = FileUtil.class.getSimpleName();
    public static final int SIZETYPE_B = 1;// 获取文件大小单位为B的double值
    public static final int SIZETYPE_KB = 2;// 获取文件大小单位为KB的double值
    public static final int SIZETYPE_MB = 3;// 获取文件大小单位为MB的double值
    public static final int SIZETYPE_GB = 4;// 获取文件大小单位为GB的double值
    /**
     * 获取文件指定文件的指定单位的大小
     *
     * @param filePath
     *            文件路径
     * @param sizeType
     *            获取大小的类型1为B、2为KB、3为MB、4为GB
     * @return double值的大小
     */
    public static double getFileOrFilesSize(String filePath, int sizeType) {
        File file = new File(filePath);
        long blockSize = 0;
        try {
            if (file.isDirectory()) {
                blockSize = getFileSizes(file);
            } else {
                blockSize = getFileSize(file);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return FormetFileSize(blockSize, sizeType);
    }
    /**
     * 调用此方法自动计算指定文件或指定文件夹的大小
     *
     * @param filePath
     *            文件路径
     * @return 计算好的带B、KB、MB、GB的字符串
     */
    public static String getAutoFileOrFilesSize(String filePath) {
        File file = new File(filePath);
        long blockSize = 0;
        try {
            if (file.isDirectory()) {
                blockSize = getFileSizes(file);
            } else {
                blockSize = getFileSize(file);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return FormetFileSize(blockSize);
    }

    public static long getFolderOrFilesSize(String filePath) {
        File file = new File(filePath);
        long blockSize = 0;
        try {
            if (file.isDirectory()) {
                blockSize = getFileSizes(file);
            } else {
                blockSize = getFileSize(file);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return blockSize;
    }

    /**
     * 转换文件大小
     *
     * @param fileS
     * @return
     */
    public static String formetFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        String wrongSize = "0B";
        if (fileS == 0) {
            return wrongSize;
        }
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "KB";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "MB";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "GB";
        }
        return fileSizeString;
    }
    /**
     * 获取指定文件大小
     *
     * @return
     * @throws Exception
     */
    private static long getFileSize(File file) throws Exception {
        long size = 0;
        if (file.exists()) {
            FileInputStream fis = null;
            fis = new FileInputStream(file);
            size = fis.available();
        } else {
            file.createNewFile();
        }
        return size;
    }
    /**
     * 获取指定文件夹
     *
     * @param f
     * @return
     * @throws Exception
     */
    private static long getFileSizes(File f) throws Exception {
        long size = 0;
        File flist[] = f.listFiles();
        for (int i = 0; i < flist.length; i++) {
            if (flist[i].isDirectory()) {
                size = size + getFileSizes(flist[i]);
            } else {
                size = size + getFileSize(flist[i]);
            }
        }
        return size;
    }
    /**
     * 转换文件大小
     *
     * @param fileS
     * @return
     */
    private static String FormetFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        String wrongSize = "0B";
        if (fileS == 0) {
            return wrongSize;
        }
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "KB";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "MB";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "GB";
        }
        return fileSizeString;
    }
    /**
     * 转换文件大小,指定转换的类型
     *
     * @param fileS
     * @param sizeType
     * @return
     */
    private static double FormetFileSize(long fileS, int sizeType) {
        DecimalFormat df = new DecimalFormat("#.00");
        double fileSizeLong = 0;
        switch (sizeType) {
            case SIZETYPE_B:
                fileSizeLong = Double.valueOf(df.format((double) fileS));
                break;
            case SIZETYPE_KB:
                fileSizeLong = Double.valueOf(df.format((double) fileS / 1024));
                break;
            case SIZETYPE_MB:
                fileSizeLong = Double.valueOf(df.format((double) fileS / 1048576));
                break;
            case SIZETYPE_GB:
                fileSizeLong = Double.valueOf(df
                        .format((double) fileS / 1073741824));
                break;
            default:
                break;
        }
        return fileSizeLong;
    }

    /**
     * 删除路径指向的文件
     * @param  filePath   文件的名称
     * @return true删除成功，false删除失败
     */
    public static boolean deleteFile(String filePath)
    {
        File file = getFileByPath(filePath);
        if (null != file && file.isFile())
        {
            return file.delete();
        }
        return false;
    }

    /**
     * 获取文件路径
     * @param filePath String
     * @return 文件路径
     */
    @SuppressLint("SdCardPath")
    public static File getFileByPath(String filePath)
    {
        filePath = filePath.replaceAll("\\\\", "/");
        boolean isSdcard = false;
        int subIndex = 0;
        if (filePath.indexOf("/sdcard") == 0)
        {
            isSdcard = true;
            subIndex = 7;
        }
        else if (filePath.indexOf("/mnt/sdcard") == 0)
        {
            isSdcard = true;
            subIndex = 11;
        }

        if (isSdcard)
        {
            if (isExistSdcard())
            {
                //获取SDCard目录,2.2的时候为:/mnt/sdcard  2.1的时候为：/sdcard，所以使用静态方法得到路径会好一点。
                File sdCardDir = Environment.getExternalStorageDirectory();
                String fileName = filePath.substring(subIndex);
                return new File(sdCardDir, fileName);
            }
            else if (isEmulator())
            {
                File sdCardDir = Environment.getExternalStorageDirectory();
                String fileName = filePath.substring(subIndex);
                return new File(sdCardDir, fileName);
            }
            return null;
        }
        else
        {
            return new File(filePath);
        }
    }

    /**
     * 是否有sdcard
     * @return boolean
     */
    public static boolean isExistSdcard()
    {
        if (!isEmulator())
        {
            return Environment.getExternalStorageState()
                    .equals(Environment.MEDIA_MOUNTED);
        }
        return true;
    }

    /**
     *
     * @param url
     * @return      xx.xx
     */
    public static String getNameByUrl(String url){
        String[] paramsSpilt = url.split("\\?");
        String[] spilt = paramsSpilt[0].split("/");
        String name = spilt[spilt.length - 1];
        return name;
    }

    /**
     * 是否是模拟器
     * @return boolean
     */
    public static boolean isEmulator()
    {
        return android.os.Build.MODEL.equals("sdk");
    }


    /**
     *
     * 文件转化byte[]操作
     *
     * @param file 需要转化为byte[]的文件
     * @return 文件的byte[]格式
     * @throws IOException IO流异常
     */
    public static byte[] fileToByte(File file) throws IOException
    {
        InputStream in = new FileInputStream(file);
        try
        {
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            byte[] barr = new byte[1024];
            while (true)
            {
                int r = in.read(barr);
                if (r <= 0)
                {
                    break;
                }
                buffer.write(barr, 0, r);
            }
            return buffer.toByteArray();
        }
        finally
        {
            closeStream(in);
        }
    }

    public static void closeStream(Closeable var0) {
        try {
            if(var0 != null) {
                var0.close();
            }

        } catch (IOException var1) {
            ;
        }
    }

    //往SD卡写入文件的方法
    public static boolean  savaFileToSD(String filename, byte[] bytes) throws Exception {

        try {
            File f = new File(filename);
            if(f.exists() || !f.isFile()){
                f.delete();
            }
            f.createNewFile();
            //这里就不要用openFileOutput了,那个是往手机内存中写数据的
            FileOutputStream output = new FileOutputStream(filename);
            output.write(bytes);
            //将bytes写入到输出流中
            output.close();
            //关闭输出流
            return true;
        } catch (IOException e) {

        }

        return false;
    }



    public static boolean downloadFile(String savePath,String remoteUrl){
        Log.d(TAG,"downloadFile :"+savePath+" "+remoteUrl);
        File file = new File(savePath);

        //如果目标文件已经存在，则删除。产生覆盖旧文件的效果
        if(file.exists()){
            file.delete();
        }


        try {
            file.createNewFile();
            // 构造URL
            URL url = new URL(remoteUrl);
            // 打开连接
            URLConnection con = url.openConnection();
            //获得文件的长度
            int contentLength = con.getContentLength();
            Log.d(TAG,"长度 :" + contentLength);
            // 输入流
            InputStream is = con.getInputStream();
            // 1K的数据缓冲
            byte[] bs = new byte[10240];
            // 读取到的数据长度
            int len;
            // 输出的文件流
            OutputStream os = new FileOutputStream(file);
            // 开始读取
            while ((len = is.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
            // 完毕，关闭所有链接
            os.close();
            is.close();

            return true;
        } catch (IOException e) {
            Log.d(TAG,"downloadFile IOException: "+e.toString());
            e.printStackTrace();
            if(file != null && file.exists())
            {
                file.delete();
            }
            return false;
        }

    }


}
